<template>
  <div class="app-container">
    <el-form ref="elForm" :disabled="$route.query.isInfo" :model="formData" :rules="rules" size="medium"
      label-width="120px">
      <h2 style="text-align: center">_年度实验室人员培训计划</h2>
      <h4 class="form-header h4">基本信息</h4>
      <el-row :gutter="15">
        <el-col :span="8">
          <el-form-item label="年度" prop="year">
            <el-date-picker format="yyyy" value-format="yyyy" v-model="formData.year" type="year" placeholder="选择年">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <h4 class="form-header h4">
        <el-button type="primary" plain size="mini" @click="handleAdd">增行</el-button>
        <!-- <el-button type="danger" plain size="mini" @click="handleDele"
          >删行</el-button
        > -->
      </h4>
      <el-table :data="formData.contentList" :border="true" style="width: 100%">
        <el-table-column label="序号" type="index" align="center" />
        <el-table-column label="部门" align="center" width="150">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`contentList.${scope.$index}.deptId`" :rules="rules.deptId">
              <!-- 'references'+scope.$index -->
              <el-cascader ref="references" :style="{ width: '100%' }"
                :props="{ value: 'id', checkStrictly: true, multiple: true }" :show-all-levels="false" placeholder="请选择部门"
                v-model="scope.row.deptId" :options="deptOptions" @change="changeCascaderNums($event, scope.$index)"
                @visible-change="visibleChange($event, scope.$index)"></el-cascader>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="培训方式" align="center" width="150">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`contentList.${scope.$index}.terrainType`" :rules="rules.terrainType">
              <el-select v-model="scope.row.terrainType" filterable placeholder="请选择培训方式">
                <el-option v-for="dict in dict.type.sys_cultivate_type" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="选择方式" align="center" width="150">
          <template slot-scope="scope">
            <!-- {{ scope.row.type }} -->
            <el-form-item label-width="0" :prop="`contentList.${scope.$index}.type`" :rules="rules.type">
              <el-select v-model="scope.row.type" ref="selectRef" @change="changeType($event, scope.$index)" filterable
                placeholder="请选择培训方式">
                <el-option label="人员" value="0" />
                <el-option label="部门" value="1" />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-model="userIdList" width="200" align="center">
          <div slot="header" slot-scope="scope">
            <div>选择培训人或岗位</div>
          </div>
          <div slot-scope="scope" v-if="scope.row.type == '0'">
            <el-form-item label-width="0" :prop="`contentList.${scope.$index}.userids`" :rules="rules.userids">
              <UserDialogSelection @change="chanageUser($event, scope.$index, 0)" v-model="scope.row.userids">
              </UserDialogSelection>
            </el-form-item>
          </div>
          <div slot-scope="scope" v-else>
            <el-form-item label-width="0" :prop="`contentList.${scope.$index}.userids`" :rules="rules.userids">
              <el-cascader ref="references1" :style="{ width: '100%' }"
                :props="{ value: 'id', checkStrictly: true, multiple: true }" :show-all-levels="false" placeholder="请选择部门"
                v-model="scope.row.userids" :options="deptOptions" @change="chanageUser($event, scope.$index, 1)"
                @visible-change="visibleChange1($event, scope.$index)"></el-cascader>
            </el-form-item>
          </div>

        </el-table-column>
        <!-- <el-table-column label="部门" align="center">

        </el-table-column> -->
        <el-table-column label="培训内容" align="center" width="200">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`contentList.${scope.$index}.content`" :rules="rules.content">
              <el-input v-model="scope.row.content" placeholder="请输入培训内容" @input="input"></el-input>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="实施时间" width="380" prop="price" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`contentList.${scope.$index}.time`" :rules="rules.time">
              <!-- <el-date-picker v-model="scope.row.operTime" format="yyyy-MM" type="month" value-format="yyyy-MM"
                :style="{ width: '100%' }" placeholder="请选择实施时间" clearable></el-date-picker> -->
              <el-date-picker v-model="scope.row.time" @change="changeOperTime($event, scope.$index)" type="daterange"
                value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="主讲人" align="center" width="150">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`contentList.${scope.$index}.hostUserName`" :rules="rules.hostUserName">
              <el-input v-model="scope.row.hostUserName" placeholder="请输入主讲人"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="培训成果" align="center" width="150">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`contentList.${scope.$index}.result`" :rules="rules.result">
              <el-input v-model="scope.row.result" placeholder="请输入培训成果"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" min-width="200">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`contentList.${scope.$index}.remark`" :rules="rules.remark">
              <el-input v-model="scope.row.remark" placeholder="备注"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="删除" align="center">
          <template slot-scope="scope">
            <el-button type="danger" plain size="mini" @click="handleDele(scope.$index)">删行</el-button>
          </template>
        </el-table-column>

      </el-table>

      <el-col :span="24">
        <el-form-item label-width="0" style="text-align: center; margin-top: 30px">
          <el-button v-if="!$route.query.isInfo" type="primary" @click="submitForm">提交</el-button>
          <el-button :disabled="false" @click="resetForm" v-if="!deployId">返回</el-button>
        </el-form-item>
      </el-col>
    </el-form>
  </div>
</template>

<script>
import { deptTreeSelect } from "@/api/system/user.js";

import {
  cultivateYearPlanAdd,
  updategcultivateYearPlan,
  cultivateYearPlanInfo,
} from "@/api/cultivate/yearPlan.js";
export default {
  components: {},
  dicts: ["sys_cultivate_type"],
  props: [],
  data() {
    return {
      userIdList: [],
      formData: {
        year: null,
        contentList: [
          {
            deptId: "",
            joinUserList: [],
            deptName: undefined,
            terrainType: undefined,
            operTime: null,
            operEndTime: null,
            content: undefined,
            hostUserName: undefined,
            remark: undefined,
            result: undefined,
            userids: [],
            time: [],
            type: '0'
          },
        ],
      },
      deployId: '',
      deptOptions: [],
      rules: {
        userids: [
          {
            required: true,
            message: "请选择培训人员",
            trigger: "blur",
          },
        ],
        year: [
          {
            required: true,
            message: "请选择年",
            trigger: "change",
          },
        ],
        content: [
          {
            required: true,
            message: "请输入培训内容",
            trigger: "blur",
          },
        ],
        hostUserName: [
          {
            required: true,
            message: "请输入主讲人",
            trigger: "blur",
          },
        ],
        remark: [
          {
            required: false,
            message: "请输入备注",
            trigger: "blur",
          },
        ],
        result: [
          {
            required: false,
            message: "请输入备培训成果",
            trigger: "blur",
          },
        ],
        time: [
          {
            required: true,
            message: "请选择实施时间",
            trigger: "change",
          },
        ],
        deptId: [
          {
            required: true,
            message: "请选择部门",
            trigger: "change",
          },
        ],
      },
      deptTreeSelect: [],
    };
  },
  computed: {},
  created() {
    this.deployId = this.$route.query.deployId
    if (this.$route.query.isEdit || this.$route.query.isInfo) {
      this.getinfo();
    }
    this.getDeptTree();
  },
  mounted() { },

  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    changeOperTime(e, i) {
      console.log(e);
      this.formData.contentList[i].operTime = e[0]
      this.formData.contentList[i].operEndTime = e[1]
    },
    chanageUser(e, i, l) {
      console.log(e, i);
      if (l == 0) {
        this.formData.contentList[i].joinUserList = e.map((i) => {
          return {
            userId: i.userId,
            userName: i.nickName,
            type: '0'
          };
        });
      }

    },
    visibleChange1(e, i) {
      console.log(e, this.$refs.references1.getCheckedNodes());
      let arr = this.$refs.references1.getCheckedNodes();
      this.formData.contentList[i].joinUserList = arr.map((i) => {
        return {
          userId: i.value,
          userName: i.label,
          type: '1'
        };
      });
    },
    // 选择第一个部门
    changeCascaderNums(e, i) {
      console.log(e, i);
      this.showGroup = e.length > 0 ? true : false;
    },
    visibleChange(e, i) {
      // console.log(e,i, this.$refs["references" + i].getCheckedNodes());
      if (!e && this.showGroup) {
        let arr = this.$refs.references.getCheckedNodes();
        console.log(arr);
        let list = [];
        let label = [];
        arr.forEach((item, index) => {
          list.push(item.value);
          label.push(item.label);
        });
        console.log(list);
        this.formData.contentList[i].deptIdReplace = list.toString();
        this.formData.contentList[i].deptNameReplace = label.toString();
        if (this.$route.query.isEdit) {
          this.formData.contentList[i].cultivateYearPlanId = this.$route.query.id
        }
        console.log(this.formData.contentList[i].deptNameReplace, 'this.formData.userList1[i].deptId');
      }
    },
    handleAdd() {
      this.formData.contentList.push({
        deptId: "",
        joinUserList: [],
        deptName: undefined,
        terrainType: undefined,
        operTime: null,
        operEndTime: null,
        content: undefined,
        hostUserName: undefined,
        remark: undefined,
        result: undefined,
        userids: [],
        time: [],
        type: '0'
      });
    },
    handleDele(e) {
      if (this.formData.contentList.length == 1) return;
      this.formData.contentList.splice(e, 1);
    },
    changeType(e, i) {
      this.formData.contentList[i].joinUserList = []
      if (this.$route.query.isEdit) {
        this.formData.contentList[i].content = this.formData.contentList[i].content + ' '
        this.formData.contentList[i].content = this.formData.contentList[i].content.replace(/\s/g, "");
      }
    },
    getinfo() {
      cultivateYearPlanInfo(this.$route.query.id).then((response) => {
        this.formData = response.data;
        this.formData.contentList.forEach((i) => {
          let list1 = []
          let listUesr = []

          i.time = []
          i.type = i.joinUserList[0].type.toString()
          i.deptIdReplace = i.deptId
          i.deptNameReplace = i.deptName
          i.deptId = i.deptId.split(",");
          i.deptId = i.deptId.map((i) => parseInt(i));
          i.deptId.map((i) => {
            list1.push(this.findParentLot(i));
          });
          i.deptId = list1;
          console.log(i.deptId, ' i.deptId');
          i.time.push(i.operTime, i.operEndTime)
          // 0是人员1是部门
          if (i.type == 0) {
            this.$set(i, "userids", i.joinUserList.map((e) => e.userId));
          } else {
            let arr = []
            i.joinUserList.forEach(e => {
              arr.push(e.userId)
            })

            arr.map((i) => {
              console.log(i);
              listUesr.push(this.findParentLot(i));
            });
            console.log(listUesr);
            i.userids = listUesr
            console.log(i.userids, 'i.userids');
          }

        });

      });
    },
    // / 创建新数组 返回
    findParentLot(id) {
      const arr = [];
      this.deployIdFun(this.deptOptions, id, arr);
      return arr.reverse();
    },
    // 逻辑代码 for循环 判断相同的id 取上级ID
    deployIdFun(options, id, newArr) {
      console.log(options);
      options.forEach((v) => {
        if (v.id === id) {
          newArr.push(id);
          console.log(newArr, "newArr");
          if (!v.parentId || v.parentId !== "0") {
            this.deployIdFun(this.deptOptions, v.parentId, newArr);
          }
        } else {
          if (v.children && v.children.length) {
            this.deployIdFun(v.children, id, newArr);
          }
        }
      });
    },
    input() { },

    submitForm() {
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          let query = JSON.parse(JSON.stringify(this.formData));
          query.contentList.forEach((e, i) => {
            // query.contentList[i].deptId =
            //   this.$refs["reference" + i].getCheckedNodes()[0].value;
            // query.contentList[i].deptName = this.$refs["reference" + i]
            //   .getCheckedNodes()[0]
            //   .pathLabels.pop();
            query.contentList[i].deptId = e.deptIdReplace;
            query.contentList[i].deptName = e.deptNameReplace;
          });
          console.log(query);
          if (this.formData.cultivateYearPlanId != undefined) {
            query.taskId = this.$route.query.taskId
            query.procInsId = this.$route.query.procInsId

            updategcultivateYearPlan(query).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.resetForm();
            });
          } else {
            cultivateYearPlanAdd(query).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.resetForm();
            });
          }
        }
      });
    },
    resetForm() {
      const obj = { path: "./yearPlan" };
      this.$tab.closeOpenPage(obj);
    },
  },
};
</script>
//
<style lang="scss" scoped>
::v-deep .el-form-item {
  margin-top: 20px !important;
}
</style>
